package com.liwenfeng.thread;

import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;

public class ThreadPoolTest {
    public static class RunableImpl implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "...执行了");
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService es = Executors.newFixedThreadPool(4);

//        Runnable runnable = new ThreadPoolTest.RunableImpl();
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName() + "...执行了");
        };

        Callable<String> callable1 = () -> {
            return Thread.currentThread().getName()+"------"+"callable返回值 。。。";
        };

        Supplier<Integer> callable2 = () -> {
            System.out.println(Thread.currentThread().getName());
            int sum = 0;
            for (int i = 0; i <= 100; i++) {
                sum += i;
            }
            return sum;
        };
        es.submit(runnable);
        es.submit(runnable);
        es.submit(runnable);

        Future<String> future1 = es.submit(callable1);
//        Future<Integer> future2 = es.submit(callable2);
        System.out.println(future1.get());
//        System.out.println(future2.get());

        List<CompletableFuture<Integer>> list = new ArrayList<>();
        list.add(CompletableFuture.supplyAsync(callable2,es));
        list.forEach(item-> {
            try {
                System.out.println(item.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });

        es.shutdown();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"定时任务执行了。。。");
            }
        }, new Date(),2000L);
    }
}
